import Vue from 'vue'
import VueRouter from 'vue-router'
import types from 'utils/types.js'
import { urlJointQuery } from 'utils'

// home
const Main = () => import('views/main/Main.vue')

// 发现页 discover
const Discover = () => import('views/main/container/discover/Discover.vue')
// 推荐页 recommend
const Recommend = () => import('views/main/container/discover/recommend/Recommend.vue')
// 歌单页 playlists
const Playlists = () => import('views/main/container/discover/playlists/Playlists.vue')
// 排行榜页 toplist
const TopList = () => import('views/main/container/discover/toplist/TopList.vue')
// 歌手页 artists
const Artists = () => import('views/main/container/discover/artists/Artists.vue')
// 歌单详情页 playlist/detail
const PlaylistDetail = () => import('components/content/playlistdetail/PlaylistDetail.vue')
// 搜索结果 /search/results
const SearchResult = () => import('components/content/search/results/SearchResults.vue')
// 歌手详情页
const ArtistDetail = () => import('components/content/artistdetail/ArtistDetail')

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/main'
  },
  {
    path: '/main',
    redirect: '/main/discover',
    component: Main,
    children: [
      // 发现音乐
      {
        path: '/main/discover',
        redirect: '/main/discover/recommend',
        component: Discover,
        children: [
          // 个性推荐
          {
            path: '/main/discover/recommend',
            component: Recommend
          },
          // 歌单
          {
            path: '/main/discover/playlists',
            component: Playlists
          },
          // 排行版
          {
            path: '/main/discover/toplist',
            component: TopList
          },
          // 歌手
          {
            path: '/main/discover/artists',
            component: Artists
          }
        ]
      },
      // 歌单详情
      {
        path: '/playlist/detail',
        component: PlaylistDetail
      },
      // 搜索结果
      {
        path: '/search/results',
        component: SearchResult
      },
      // 歌手详情页
      {
        path: '/artists/detail',
        component: ArtistDetail
      }
    ]
  }
]

const router = new VueRouter({
  routes
})
// 把Vue实例化放在that中
let that = null
router.beforeEach((to, from, next) => {
  // 把实例化保存在that中
  if (!that) that = router.app
  // 1. 离开页面的时候有绑定时间总线的yEnd则取消
  if (that.$bus && that.$bus._events.yEnd) {
    that.$bus.$off('yEnd')
  }
  that.$options.store.commit(types.ADD_HISTORY, urlJointQuery(to.path, to.query))
  next()
})

export default router
